/**
 * ===============================================================================
 * ==================== networkUtilV2.js,可限制请求重复发送 ========================
 * ===============================================================================
 */

const util=require('./util.js')
const Md5 = require('./md5/md5.js')


//请求记录map,格式为《requestKey,true》
let requestMap = {}

/**
 * 存入当前请求的RequestKey。
 */
export function addRequestKey(key) {
    requestMap[key] = true
}

export function removeRequestKey(key) {
    delete requestMap[key]
}

export function hitRequestKey(key) {
    return requestMap[key]
}

/**
 * 根据url,method,requestData产生requestKey。
 */
export function getRequestKey(url, method, requestData) {
    let requestKey = "url=" + url + ",method=" + method + ",requestData=" + JSON.stringify(requestData)
    requestKey = Md5.md5(requestKey).toUpperCase()
    return requestKey
}

/**
 * 通用http请求。
 */
export function http(url, requestData, method, token = null, contentType = "application/json", showLoadStatus = true) {

    /**
     * 分析是否为重复提交请求。
     */
    let requestKey = getRequestKey(url, method, requestData)
    if (hitRequestKey(requestKey)) {
        throw Error("重复提交请求!requestKey=" + requestKey)
    }
    addRequestKey(requestKey)

    //若showLoadStatus为true
    if (showLoadStatus == true) {
        wx.showLoading({
            title: '加载中...',
        });
    }

    return new Promise(function(resolve, reject) {
        wx.request({
            url: url,
            data: {
                ...requestData,
                //token: token
            },
            header: {
                'content-type': contentType,
                'USER_TOKEN': token
            },
            method: method,
            dataType: 'json',
            success: function(res) {
                //console.info("networkUtil wx.request().success().res",res)
                
                /**
                 * 从requestMap中移除requestKey
                 */
                removeRequestKey(requestKey)
                
                //若有加载等待提示
                if (showLoadStatus == true) {
                    wx.hideLoading();
                }

                /**
                 * 若res.statusCode为200，表示服务端处理了该请求。
                 */
                if (res.statusCode == 200) {
                    //若请求成功
                    if (res.data.status == 200) {
                        resolve(res.data)
                    } else if (res.data.status == 50001) {
                        /**
                         * 若token已失效。token已过期，提示用户重新登录。
                         */
                        console.info("token已过期,请重新登录!")
                        util.showToast("token已过期,请重新登录!")
                        reject(res.data)
                        
                    } else {
                        //若请求失败
                        reject(res.data)
                    }
                } else {
                    /**
                     * 服务端处理该请求时，抛出错误。
                     */
                    reject(res);
                }
            },

            fail: function(err) {
                /**
                 * 从requestMap中移除requestKey
                 */
                removeRequestKey(requestKey)
                
                //请求失败，可能网络不通。
                reject(err)
            }
        })
    })

}

/**
 * 发送GET请求。
 */
export function httpGet(url, requestData, showLoadStatus = true) {
    let method = "GET"
    let contentType = "application/json"
    let token = wx.getStorageSync("token")
    return http(url, requestData, method, token, contentType, showLoadStatus)
}

/**
 * 发送POST请求。
 */
export function httpPost(url, requestData, showLoadStatus = true) {
    let method = "POST"
    let contentType = "application/json"
    let token = wx.getStorageSync("token")
    return http(url, requestData, method, token, contentType, showLoadStatus)
}




